package org.boulderfoodrescue.webapp.client.pickups.enterpickupreport;

import java.util.Date;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DateBox.Format;

public class CustomDateBoxFormat implements Format{
	private static final String DATE_BOX_FORMAT_ERROR = "dateBoxFormatError";
	private final DateTimeFormat dateTimeFormat;

	/**
	 * Creates a new expiration date format instance.
	 */
	public CustomDateBoxFormat(){
		dateTimeFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_MEDIUM);
	}

	/**
	 * Creates a new expiration date format instance.
	 * 
	 * @param dateTimeFormat the {@link DateTimeFormat} to use with this
	 *          {@link Format}.
	 */
	public CustomDateBoxFormat(DateTimeFormat dateTimeFormat){
		this.dateTimeFormat = dateTimeFormat;
	}

	@Override
	public String format(DateBox dateBox, Date date) {
		if(date == null){
			return "";
		} else {
			return dateTimeFormat.format(date);
		}
	}

	/**
	 * Gets the date time format.
	 *
	 * @return the date time format
	 */
	public DateTimeFormat getDateTimeFormat(){
		return dateTimeFormat;
	}

	@Override
	public Date parse(DateBox dateBox, String text, boolean reportError) {
		Date date = null;
		try {
			if (text.length() > 0) {
				date = dateTimeFormat.parse(text);
			}
		} catch (IllegalArgumentException exception) {
			try {
				date = new Date(text);
			} catch (IllegalArgumentException e) {
				if (reportError) {
					dateBox.addStyleName(DATE_BOX_FORMAT_ERROR);
				}
				return null;
			}
		}
		return date;
	}

	@Override
	public void reset(DateBox dateBox, boolean abandon) {
		dateBox.removeStyleName(DATE_BOX_FORMAT_ERROR);
	}
}